/**
 * API 客户端
 * 负责与后端API进行通信
 */
class ApiClient {
  constructor() {
    this.baseUrl = '/cgi-bin';
    this.timeout = 10000; // 10秒超时
  }

  /**
   * 发送HTTP请求
   */
  async request(method, url, data = null) {
    const requestUrl = `${this.baseUrl}${url}`;
    
    const options = {
      method: method.toUpperCase(),
      headers: {
        'Content-Type': 'application/json',
      },
    };

    if (data && (method.toUpperCase() === 'POST' || method.toUpperCase() === 'PUT')) {
      options.body = JSON.stringify(data);
    }

    try {
      console.log(`[API] ${method.toUpperCase()} ${requestUrl}`, data);
      
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), this.timeout);
      options.signal = controller.signal;

      const response = await fetch(requestUrl, options);
      clearTimeout(timeoutId);

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();
      console.log(`[API] Response:`, result);
      
      return result;
    } catch (error) {
      console.error(`[API] Error:`, error);
      throw error;
    }
  }

  /**
   * GET 请求
   */
  async get(url) {
    return this.request('GET', url);
  }

  /**
   * POST 请求
   */
  async post(url, data) {
    return this.request('POST', url, data);
  }

  /**
   * PUT 请求
   */
  async put(url, data) {
    return this.request('PUT', url, data);
  }

  /**
   * DELETE 请求
   */
  async delete(url) {
    return this.request('DELETE', url);
  }

  // === 项目管理 API ===

  /**
   * 获取项目列表
   */
  async getProjects() {
    return this.get('/projects');
  }

  /**
   * 获取单个项目详情
   */
  async getProject(projectId) {
    return this.get(`/projects/${projectId}`);
  }

  /**
   * 创建新项目
   */
  async createProject(name) {
    return this.post('/projects', { name });
  }

  /**
   * 重命名项目
   */
  async renameProject(projectId, name) {
    return this.put(`/projects/${projectId}/rename`, { name });
  }

  /**
   * 删除项目
   */
  async deleteProject(projectId) {
    return this.delete(`/projects/${projectId}`);
  }

  // === 环境管理 API ===

  /**
   * 更新环境配置
   */
  async updateEnvironment(projectId, environment, config) {
    return this.put(`/projects/${projectId}/environments/${environment}`, { config });
  }

  /**
   * 激活环境
   */
  async activateEnvironment(projectId, environment) {
    return this.post(`/projects/${projectId}/environments/${environment}/activate`);
  }

  /**
   * 停用环境
   */
  async deactivateEnvironment(projectId) {
    return this.post(`/projects/${projectId}/environments/deactivate`);
  }

  // === 自定义规则 API ===

  /**
   * 添加自定义规则
   */
  async addCustomRule(projectId, label, value) {
    return this.post(`/projects/${projectId}/custom-rules`, { label, value });
  }

  /**
   * 更新自定义规则
   */
  async updateCustomRule(projectId, ruleId, updates) {
    return this.put(`/projects/${projectId}/custom-rules/${ruleId}`, updates);
  }

  /**
   * 删除自定义规则
   */
  async deleteCustomRule(projectId, ruleId) {
    return this.delete(`/projects/${projectId}/custom-rules/${ruleId}`);
  }

  /**
   * 激活自定义规则
   */
  async activateCustomRule(projectId, ruleId) {
    return this.post(`/projects/${projectId}/custom-rules/${ruleId}/activate`);
  }

  // === 系统信息 API ===

  /**
   * 获取统计信息
   */
  async getStats() {
    return this.get('/stats');
  }

  /**
   * 获取激活的环境列表
   */
  async getActiveEnvironments() {
    return this.get('/active-environments');
  }

  /**
   * 健康检查
   */
  async health() {
    return this.get('/health');
  }

  /**
   * 获取插件信息
   */
  async getInfo() {
    return this.get('/info');
  }

  /**
   * 重置所有配置（调试用）
   */
  async reset() {
    return this.post('/reset');
  }
}

// 创建全局API客户端实例
window.api = new ApiClient();